package com.bajiao.admin.controller.coupon;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bajiao.common.api.vo.Result;
import com.bajiao.common.constant._Whole;
import com.bajiao.entity.coupon.Coupon;
import com.bajiao.entity.product.Product;
import com.bajiao.entity.store.Store;
import com.bajiao.entity.user.UserCoupon;
import com.bajiao.service.coupon.CouponService;
import com.bajiao.service.store.StoreService;
import com.bajiao.service.user.UserCouponService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.bajiao.admin.base.AdminBaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 优惠券表
 * @Author: FanJq
 * @Date: 2024-12-12
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "优惠券表")
@RestController
@RequestMapping("/coupon")
public class CouponController extends AdminBaseController<Coupon, CouponService> {
    @Autowired
    private CouponService couponService;
    @Resource
    private UserCouponService userCouponService;

    /**
     * @return
     * @description: 分页列表查询
     * @author: FanJq
     * @date: 2024-12-12
     */
    @ApiOperation(value = "优惠券表-分页列表查询", notes = "优惠券表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(String title, String scope, Integer type) {
        LambdaQueryWrapper<Coupon> sqlQuery = new LambdaQueryWrapper<>();
        startPage();
        sqlQuery.like(StrUtil.isNotBlank(title), Coupon::getTitle, title);
        sqlQuery.eq(ObjectUtil.isNotNull(type), Coupon::getType, type);
        if (StrUtil.isNotBlank(scope)) {
            if (StrUtil.equals("000", scope)) {
                sqlQuery.eq(Coupon::getScope, 1);
            } else {
                sqlQuery.eq(Coupon::getScope, 2);
                sqlQuery.eq(Coupon::getStoreId, scope);
            }
        }
        sqlQuery.orderByDesc(Coupon::getCreateTime);
        List<Coupon> couponList = couponService.list(sqlQuery);
        couponList.forEach(coupon -> {
            coupon.setTotal(userCouponService
                    .lambdaQuery()
                    .eq(UserCoupon::getCouponId, coupon.getId())
                    .gt(UserCoupon::getStatus, _Whole.ZERO)
                    .count());
        });
        return Result.ok(getDataTable(couponList));
    }

    /**
     * @param coupon
     * @return
     * @description: 添加
     * @author: FanJq
     * @date: 2024-12-12
     */
    @ApiOperation(value = "优惠券表-添加", notes = "优惠券表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody Coupon coupon) {
        if (coupon.getType() == 1) {
            coupon.setQuota(coupon.getQuota().divide(new BigDecimal("10"), 2));
        }
        couponService.save(coupon);
        return Result.ok("添加成功！");
    }

    /**
     * @param coupon
     * @return
     * @description: 编辑
     * @author: FanJq
     * @date: 2024-12-12
     */
    @ApiOperation(value = "优惠券表-编辑", notes = "优惠券表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody Coupon coupon) {
        couponService.updateById(coupon);
        return Result.ok("编辑成功!");
    }

    @ApiOperation(value = "产品表-编辑", notes = "产品表-编辑")
    @PutMapping(value = "/handle/status")
    public Result<?> handleStatus(@RequestBody Coupon request) {
        Coupon coupon = couponService.getById(request.getId());
        Integer status = coupon.getStatus() == 0 ? 1 : 0;
        couponService.lambdaUpdate().set(Coupon::getStatus, status).eq(Coupon::getId, coupon.getId()).update();
        return Result.ok(status == 0 ? "已禁用" : "已启用");
    }

    /**
     * @param id
     * @return
     * @description: 通过id删除
     * @author: FanJq
     * @date: 2024-12-12
     */
    @ApiOperation(value = "优惠券表-通过id删除", notes = "优惠券表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        couponService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * @param ids
     * @return
     * @description: 批量删除
     * @author: FanJq
     * @date: 2024-12-12
     */
    @ApiOperation(value = "优惠券表-批量删除", notes = "优惠券表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.couponService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * @param id
     * @return
     * @description: 通过id查询
     * @author: FanJq
     * @date: 2024-12-12
     */
    @ApiOperation(value = "优惠券表-通过id查询", notes = "优惠券表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        Coupon coupon = couponService.getById(id);
        return Result.ok(coupon);
    }

    /**
     * @param request
     * @param coupon
     * @description: 导出excel
     * @author: FanJq
     * @date: 2024-12-12
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Coupon coupon) {
        return super.exportXls(request, coupon, Coupon.class, "优惠券表");
    }

    /**
     * @param request
     * @param response
     * @return
     * @description: 通过excel导入数据
     * @author: FanJq
     * @date: 2024-12-12
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Coupon.class);
    }

    @Resource
    private StoreService storeService;

    @ApiOperation(value = "优惠券表-通过id查询", notes = "优惠券表-通过id查询")
    @GetMapping(value = "/test/{num}")
    public Result<?> test(@PathVariable Integer num) {
        // 查询所有店铺
        List<Store> list = storeService.list();
        for (Store store : list) {
            Coupon coupon = new Coupon();
            coupon.setTitle(store.getTitle());
            coupon.setPrice(new BigDecimal(num));
            coupon.setType(2);
            coupon.setScope(2);
            coupon.setReceiveWay(3);
            coupon.setDays(100);
            coupon.setStoreId(store.getId());
            coupon.setStatus(1);
            coupon.setQuota(new BigDecimal(num));
            if(num == 20){
                coupon.setCount(10000);
            }
            if(num == 30){
                coupon.setCount(2000);
            }
            couponService.save(coupon);
        }
        return Result.ok();
    }


}
